'''
Created on 20/03/2011

@author: lctr30
'''

import os.path
from core.pemba import Pemba

class MSG:
    BASENAME = 'Basename: {0}'
    DIRNAME = 'Dirname: {0}'
    pass

class CONST:
    NL = '\n'
    EQ = '='
    EMPTY = ''

class MODE:
    READ = 'r'
    WRITE = 'w'
    READ_WRITE='rw'

class Propreader(Pemba):
    def __init__(self, filename):
        Pemba.__init__(self)
        self.map = {}
        self.names = []
        self.values = []
        self.filename = self.__get_file__(filename)
        self.__read__()

    def __get_file__(self, filename):
        basename = os.path.basename(filename)
        self.INFO(MSG.BASENAME,basename)
        dirname = os.path.dirname(filename)
        self.INFO(MSG.DIRNAME,dirname)
        if not  os.path.exists(dirname):
            os.makedirs(dirname)
        return filename
        
    def __add_attr__(self, name, value):
        try:
            value = int(value)
            setattr(self, name, value)
            return
        except:
            pass
        setattr(self, name, value)


    def __read__(self):
        if not os.path.exists(self.filename):
            fp = open(self.filename, MODE.WRITE)
            fp.close()
        fp = open(self.filename, MODE.READ)
        buf = fp.read()
        lines = buf.split(CONST.NL)
        for line in lines:
            if line.find(CONST.EQ) != -1:
                arr = line.split(CONST.EQ)
                name = arr[0]
                value = CONST.EQ.join(arr[1:])
                self.__add_attr__(name, value)
                self.names.append(name)
                self.values.append(value)
            else:
                self.names.append(line.strip())
                self.values.append(CONST.EMPTY)
        fp.close()
                
    def add_prop(self, name, value):
        self.__add_attr__(name, value)
    
    def remove_prop(self, name):
        if name in self.names:
            index = self.names.index(name)
            self.names.pop(index)
            self.values.pop(index)
        if hasattr(self, name):
            delattr(self, name)
    
    def save(self):
        fp = open(self.filename, MODE.WRITE)
        for i in range(len(self.names)):
            name = self.names[i]
            value = self.values[i]
            if len(name.strip()) != 0 and len(value) != 0:
                value = self.values[i]
                line = CONST.EQ.join([name, value])
                fp.write(line)
                fp.write(CONST.NL)
            else:
                print len(self.names), i
                if len(name) > 0:
                    fp.write(name.strip())
                    fp.write(CONST.NL)
                elif len(self.names) -1 != i:
                    fp.write(CONST.NL)
            
        fp.close()
        
        
if __name__=='__main__':
    filename = '/home/lctr30/test_dir/test1/props.prop'
    p = Propreader(filename)
    print p.key1
    p.save()

    